package csx.study.demo.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import csx.study.demo.dto.UserDTO;
import csx.study.demo.entity.User;
import csx.study.demo.properties.JwtProperties;
import csx.study.demo.service.IUserService;
import csx.study.demo.utils.JwtUtils;
import csx.study.demo.utils.UserHolder;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 用户jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private IUserService userService;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    //TODO 搞懂这几个参数
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 判断当前拦截到的是Controller的方法还是其他资源
//        if (!(handler instanceof HandlerMethod)) {
//            // 当前拦截到的不是动态方法，直接放行
//            return true;
//        }

        // 从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getTokenName());

        if(StringUtils.isBlank(token)){
            response.setStatus(401);
            return false;
        }

        // 校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtils.parseJWT(jwtProperties.getSecretKey(), token);

            //claims中只存id
            Long id = Long.valueOf(claims.get("id").toString());

            User user = userService.lambdaQuery().eq(User::getId,id).one();

            //用户不存在
            if(user==null){
                response.setStatus(401);
                return false;
            }

            //TODO 留意拦截之后怎么传参给Controller，是只用ThreadLocal还是用其他方案
            //放入ThreadLocal，是优雅的方案
            //其他方案：用HttpServletRequest request传进去
            UserHolder.saveUser(BeanUtil.toBean(user, UserDTO.class));

            // 通过，放行
            return true;

        } catch (Exception ex) {
            // 不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }
}
